<template>
	<div>
		<div class="box">
			<!-- {{ formData.sequenceNumber }} -->
			<el-collapse v-model="activeNames" class="collapse">
				<el-collapse-item name="1">
					<template slot="title">
						<div class="nav">
							<div class="title" @click.stop="showCollapse">
								{{
									details.carType == '2' &&
									details.carSourceType == '2'
										? '车辆报价'
										: '车型报价'
								}}
								{{ index }}
							</div>
							<div></div>
						</div>
					</template>
					<!-- <div class="chunk"> -->
					<!-- <div class="title">保险</div> -->
					<!-- <div class=""> -->
					<!-- <InsuranceInfoTable -->
					<!-- v-if="details.carSourceType == '3'" -->
					<!-- ref="InsuranceInfoTable" -->
					<!-- v-model="formData" -->
					<!-- :state="state" -->
					<!-- :type="type" -->
					<!-- :index="index"></InsuranceInfoTable> -->
					<!-- <InsuranceInfo -->
					<!-- ref="InsuranceInfo" -->
					<!-- v-if=" -->
					<!-- details.carSourceType == '1' || -->
					<!-- details.carSourceType == '2' -->
					<!-- " -->
					<!-- v-model="formData" -->
					<!-- :state="state" -->
					<!-- :type="type" -->
					<!-- @initDetaultInsuranceList=" -->
					<!-- initDetaultInsuranceList -->
					<!-- " -->
					<!-- :index="index"></InsuranceInfo> -->
					<!--  -->
					<!-- <div class="content_table" v-if="showInsuranceList"> -->
					<!-- <div class="content_table-title"> -->
					<!-- 商业险险种 -->
					<!-- </div> -->
					<!-- <div :key="formData.insuranceStandardType"> -->
					<!-- <el-form -->
					<!-- :model="formData" -->
					<!-- ref="form" -->
					<!-- label-width="5px" -->
					<!-- :inline="false" -->
					<!-- size="normal" -->
					<!-- :hide-required-asterisk="true"> -->
					<!-- <el-table -->
					<!-- ref="multipleTable" -->
					<!-- :data="formData.insuranceList" -->
					<!-- tooltip-effect="dark" -->
					<!-- style="width: 100%" -->
					<!-- :header-cell-class-name=" -->
					<!-- setHeaderCellName -->
					<!-- "> -->
					<!-- <el-table-column -->
					<!-- v-if="state == 'readonly'" -->
					<!-- width="100px" -->
					<!-- align="center"> -->
					<!-- <template slot-scope="scope"> -->
					<!-- <i -->
					<!-- class="el-icon-check" -->
					<!-- v-if=" -->
					<!-- !( -->
					<!-- scope.row -->
					<!-- .operationType == -->
					<!-- '2' && -->
					<!-- scope.row -->
					<!-- .selectedType == -->
					<!-- '2' -->
					<!-- ) -->
					<!-- "></i> -->
					<!-- </template> -->
					<!-- </el-table-column> -->
					<!-- <el-table-column -->
					<!-- label="操作" -->
					<!-- width="100" -->
					<!-- align="center" -->
					<!-- v-if="state == 'write'"> -->
					<!-- <template slot-scope="scope"> -->
					<!-- <el-checkbox -->
					<!-- v-if=" -->
					<!-- scope.row -->
					<!-- .operationType == -->
					<!-- '2' -->
					<!-- " -->
					<!-- true-label="1" -->
					<!-- false-label="2" -->
					<!-- v-model=" -->
					<!-- scope.row -->
					<!-- .selectedType -->
					<!-- " -->
					<!-- :disabled=" -->
					<!-- formData.insuranceStandardType !== -->
					<!-- '4' -->
					<!-- "></el-checkbox> -->
					<!-- <div v-else> -->
					<!-- <el-button -->
					<!-- type="text" -->
					<!-- @click=" -->
					<!-- remove( -->
					<!-- scope.$index, -->
					<!-- scope.row, -->
					<!-- formData.insuranceList, -->
					<!-- ) -->
					<!-- "> -->
					<!-- 删除 -->
					<!-- </el-button> -->
					<!-- </div> -->
					<!-- </template> -->
					<!-- </el-table-column> -->
					<!--  -->
					<!-- <TableCloumn -->
					<!-- v-for="( -->
					<!-- item, index -->
					<!-- ) in tableCloumns" -->
					<!-- :cellOptions="item" -->
					<!-- dataName="insuranceList" -->
					<!-- :state="state"></TableCloumn> -->
					<!-- </el-table> -->
					<!-- </el-form> -->
					<!-- <div -->
					<!-- class="btn" -->
					<!-- @click="add(formData.insuranceList)" -->
					<!-- v-if="state == 'write'"> -->
					<!-- <i class="el-icon-plus"></i> -->
					<!-- <span>增加其他商业险种</span> -->
					<!-- </div> -->
					<!-- </div> -->
					<!--  -->
					<!-- <div v-if="details.carSourceType == '2'"> -->
					<!-- <FormItems -->
					<!-- ref="form1" -->
					<!-- v-model="formData" -->
					<!-- :form="formList" -->
					<!-- :state="state"></FormItems> -->
					<!-- </div> -->
					<!-- </div> -->
					<!-- </div> -->
					<!-- </div> -->
					<!-- 维保 -->
					<!-- <Maintain -->
					<!-- ref="Maintain" -->
					<!-- v-model="formData" -->
					<!-- :state="state" -->
					<!-- :type="type" -->
					<!-- :index="index"></Maintain> -->
					<!-- 上牌 -->
					<License
						ref="License"
						v-model="formData"
						v-if="details.carSourceType !== '2'"
						:state="state"
						:type="type"
						:index="index"></License>

					<div class="chunk">
						<div class="title carInfo">车辆信息</div>
						<div class="infoAll">
							<CarInfo
								ref="CarInfo"
								v-model="formData.plan"
								v-if="details.carSourceType == '2'"
								:state="state"
								:type="type"
								@getDecorationList="getDecorationList"
								:index="index"></CarInfo>
							<CarTypeInfo
								ref="CarTypeInfo"
								v-model="formData.plan"
								v-if="
									details.carSourceType == '1' ||
									details.carSourceType == '3'
								"
								:state="state"
								:type="type"
								@getDecorationList="getDecorationList"
								:index="index"></CarTypeInfo>
							<!-- v-if=" details.carSourceType == '1' || -->
							<!-- (details.carSourceType == '3' && showTable) " -->
							<InsurancePrice
								v-if="
									details.carSourceType == '1' ||
									details.carSourceType == '3'
								"
								ref="InsurancePrice"
								v-model="formData"
								:state="state"
								:type="type"
								:showTable="showTable"
								:index="index"></InsurancePrice>
							<Replace
								v-if="
									!(
										config.businessSource == '1' &&
										details.rentType_raw == '2'
									)
								"
								ref="Replace"
								v-model="formData"
								:state="state"
								:type="type"
								:index="index"></Replace>
							<Refitted
								ref="Refitted"
								v-model="formData"
								:state="state"
								:type="type"
								:index="index"></Refitted>
							<Other
								ref="Other"
								v-model="formData"
								:state="state"
								:type="type"
								:index="index"></Other>
							<!--  v-model="formData.feeList" -->
						</div>
					</div>
					<PricePlan
						ref="PricePlan"
						v-model="formData"
						:state="state"
						:type="type"
						:env="env"
						:index="index"></PricePlan>

					<div
						v-if="state !== 'readonly' && state !== 'disabled'"
						class="handleBox">
						<!-- v-if="details.carSourceType !== '3'" -->
						<el-button
							type="text"
							@click.stop="compute(true)"
							icon="el-icon-refresh">
							测算
						</el-button>
						<el-button
							type="text"
							@click.stop="push"
							icon="el-icon-circle-plus-outline">
							新增
						</el-button>
						<el-button
							type="text"
							@click.stop="pop"
							icon="el-icon-remove"
							v-if="
								details.productList &&
								details.productList.length > 1
							">
							删除
						</el-button>
					</div>
				</el-collapse-item>
			</el-collapse>
		</div>
	</div>
</template>

<script>
	import TableCloumn from '@/views/finance/manage/tableColumn/index.vue';
	import FormItems from '@/views/finance/manage/formItems/index.vue';
	import FormItem from '@/views/finance/reimburs/formItem/index.vue';
	import InsuranceInfo from '../carInfoChunk/insuranceInfo';
	import InsuranceInfoTable from '../carInfoChunk/insuranceInfoTable';
	import CarInfo from '../carInfoChunk/carInfo';
	import CarTypeInfo from '../carInfoChunk/carTypeInfo';
	import Replace from '../carInfoChunk/replace';
	import InsurancePrice from '../carInfoChunk/insurancePrice';
	import Refitted from '../carInfoChunk/refitted';
	import Other from '../carInfoChunk/other';
	import PricePlan from '../carInfoChunk/pricePlan';
	import Maintain from '../carInfoChunk/maintain';
	import License from '../carInfoChunk/license';
	import Test from '../carInfoChunk/test';
	import * as apis from '@/api/quota/forecast/edit/api.js';
	export default {
		components: {
			InsuranceInfo,
			InsuranceInfoTable,
			FormItems,
			FormItem,
			CarInfo,
			CarTypeInfo,
			InsurancePrice,
			Replace,
			Refitted,
			Other,
			PricePlan,
			Maintain,
			License,
			TableCloumn,
			Test,
		},
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
			index: {
				required: false,
			},
			env: {
				required: false,
				default: '',
			},
			planDicts: {
				required: false,
				default: () => {
					return [];
				},
			},
			cityList: {
				required: false,
				default: () => {
					return [];
				},
			},
			// insuranceList: {
			//     required: false,
			//     default: () => {
			//         return [];
			//     },
			// },
		},

		dicts: [
			'quota_insurance_buy_mode',
			'quota_item_operation_type',
			'quota_irrespective_type',
			'quota_maintenance_type',
			'quota_item_quota_type',

			// "pro_duct_in_sur_ance_a",
			// "pro_duct_in_sur_ance_b",
			// "pro_duct_in_sur_ance_c",
		],
		data() {
			return {
				activeNames: '1',
				dicts: {
					insuranceBuyModeType12: [
						{
							value: '1',
							label: '我司购买',
						},
						{
							value: '2',
							label: '店保',
						},
					],
					insuranceBuyModeType3: [
						{
							value: '3',
							label: '客户自购',
						},
					],
					productA: [],
					productB: [],
					productC: [],
				},
				refittedList: [],
				stateList: new Map(),
				insuranceList: [],
			};
		},
		provide() {
			return {
				_planDicts: () => this.planDicts,
				_cityList: () => this.cityList,
				_insuranceList: () => this.insuranceList,
				_currentFormData: () => this.formData,
				_refittedList: () => this.refittedList,
				_index: () => this.index,
			};
		},
		watch: {
			showInsuranceList(val, oldVal) {
				if (val == false) {
					// this.$set(this.formData, 'insuranceList', []);
				}
				if (oldVal == false && val == true) {
					// this.formData.insuranceStandardType = "4";
					// this.initDetaultInsuranceList("4");
				}
			},
			insuranceCompulsoryDiffAmount_dif: {
				handler(val) {
					this.formData.insuranceCompulsoryDiffAmount = val;
				},
				immediate: true,
			},
			insuranceCarvesselDiffAmount_dif: {
				handler(val) {
					this.formData.insuranceCarvesselDiffAmount = val;
				},
				immediate: true,
			},
			insuranceCommercialDiffAmount_dif: {
				handler(val) {
					this.formData.insuranceCommercialDiffAmount = val;
				},
				immediate: true,
			},
			'formData.insuranceStandardType': {
				handler(val) {
					// this.initDetaultInsuranceList(val, true);
				},
				// immediate: true,
			},
		},
		inject: ['details_forecast', 'details_config', '_from'],
		computed: {
			formData: {
				get() {
					return this.useVModel.call(this);
				},
				set(val) {
					this.$emit('input', val);
				},
			},
			config() {
				let config = this.details_config();
				return config;
			},
			details() {
				return this.details_forecast();
			},
			// insuranceList() {
			//     return this?._insuranceList?.() ?? [];
			// },
			showInsuranceList() {
				return (
					this.details.carSourceType !== '3' ||
					(this.details.carSourceType == '3' && this.showTable)
				);
			},
			defaultsumInsurList() {
				let arr = [];
				this.dict.type.quota_item_quota_type.map(item => {
					arr.push(item.value);
				});
				return arr;
			},
			tableCloumns() {
				return [
					{
						label: '险种',
						prop: 'insuranceItemNameVal',
						type: (row, index) => {
							if (
								this.formData.insuranceList[index]
									?.operationType == '2'
							) {
								return 'text';
							} else {
								return 'input';
							}
						},
						fitContent: false,
						rules: true,
					},

					// {
					//     label: "不计免赔",
					//     prop: "irrespectiveType",
					//     type: "checkbox",
					//     prototype: {
					//         trueLabel: "1",
					//         falseLabel: "2",
					//     },
					// },
					{
						label: '保额',
						prop: 'sumInsuredVal',
						type: (row, index) => {
							return 'input_number';
						},
						tag: 'price',
						array: true,
						selectList: (row, index) => {
							let arr = [];
							try {
								arr = JSON.parse(
									this.formData.insuranceList[index]
										?.coverageAmountList,
								);
							} catch (error) {}
							return arr;
						},
						fitContent: false,
						show: this.type == 'preview',
					},
					{
						label: '保额',
						prop: 'sumInsuredVal',
						show: this.type !== 'preview',
						type: (row, index) => {
							if (
								this.formData.insuranceList[index]
									?.operationType !== '2'
							) {
								return 'input_number';
							}
							if (
								this.formData.insuranceList[index]
									?.isCoverageAmount *
									1 ==
								1
							) {
								return 'select';
							} else {
								return 'text';
							}
						},
						format: (row, index) => {
							let arr = [];
							try {
								arr = JSON.parse(row.coverageAmountList);
							} catch (error) {}

							if (
								this.Empty(row.sumInsuredVal) &&
								this.Empty(arr) &&
								row.operationType == '2'
							) {
								if (row.selectedType == '1') {
									return '加入';
								} else {
									return '未加入';
								}
							}
							return row.sumInsuredVal;
						},
						array: true,
						selectList: (row, index) => {
							let arr = [];
							try {
								arr = JSON.parse(
									this.formData.insuranceList[index]
										?.coverageAmountList,
								);
							} catch (error) {}
							return arr;
						},
						fitContent: false,
						state: (row, index) => {
							return this.state == 'readonly'
								? 'readonly'
								: this.formData.insuranceStandardType == '4' ||
								  row?.operationType == '1'
								? 'write'
								: 'disabled';
						},

						rules: (row, index) => {
							if (
								this.formData.insuranceList[index]
									?.selectedType == '2'
							) {
								return false;
							}
							return true;
						},
					},
				];
			},

			showTable() {
				let result = false;
				let list = this.formData?.insuranceConfList ?? [];
				for (let index = 0; index < list.length; index++) {
					const element = list[index];
					if (
						element.purchaserType == '2' ||
						element.purchaserType == '3'
					) {
						result = true;
						break;
					}
				}
				return result;
			},
			insuranceCompulsoryDiffAmount_dif() {
				let res =
					this.formData?.insuranceCompulsoryCurrentAmount -
					this.formData?.insuranceCompulsoryQuondamAmount;

				if (Number.isFinite(res)) {
					return res;
				} else {
					return undefined;
				}
			},
			insuranceCarvesselDiffAmount_dif() {
				let res =
					this.formData?.insuranceCarvesselCurrentAmount -
					this.formData?.insuranceCarvesselQuondamAmount;

				if (Number.isFinite(res)) {
					return res;
				} else {
					return undefined;
				}
			},
			insuranceCommercialDiffAmount_dif() {
				let res =
					this.formData?.insuranceCommercialCurrentAmount -
					this.formData?.insuranceCommercialQuondamAmount;

				if (Number.isFinite(res)) {
					return res;
				} else {
					return undefined;
				}
			},
			formList() {
				return [
					{
						label: '保险公司',
						type: 'select',
						prop: 'insuranceCompanyKey',
						selectList: this.dict.type.in_su_rance_com_pany,
						rules: true,
						show: this.details.carSourceType == '3',
						event: {
							type: 'change',
							cb: () => {
								let item =
									this.dict.type.in_su_rance_com_pany.find(
										e => e.value == row.insuranceCompanyKey,
									);
								if (item) {
									this.formData.insuranceCompanyVal =
										item.label;
								}
							},
						},
					},
					// {
					// 	label: '增值服务特约条款',
					// 	type: 'radioGroup',
					// 	radioGroupList:
					// 		this.dict.type.quota_added_services_type,
					// 	prop: 'addedServicesType',
					// 	rules: true,
					// 	show: this.details.carSourceType == '3',
					// },
					{
						label: '交强险测算金额(年)',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCompulsoryQuondamAmount',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						tag: 'price',
					},
					{
						label: '本次交强险金额(年)',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCompulsoryCurrentAmount',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						tag: 'price',
						event: {
							type: 'change',
							cb: row => {
								if (
									this.notEmpty(
										row.insuranceCompulsoryCurrentAmount,
									)
								) {
									this.formData.planConf.insuranceCompulsoryCurrentAmount_state =
										'changed';
								} else {
									this.formData.planConf.insuranceCompulsoryCurrentAmount_state =
										'';
								}
							},
						},
					},
					{
						label: '交强险差价',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCompulsoryDiffAmount',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						min: -Infinity,
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '车船税测算金额(年)',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCarvesselQuondamAmount',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						tag: 'price',
					},
					{
						label: '本次车船税金额(年)',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCarvesselCurrentAmount',
						state:
							this.type == 'preview'
								? 'readonly'
								: this.formData.plan.isGreen == 1
								? 'disabled'
								: 'write',
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						event: {
							type: 'change',
							cb: row => {
								if (
									this.notEmpty(
										row.insuranceCarvesselCurrentAmount,
									)
								) {
									this.formData.planConf.insuranceCarvesselCurrentAmount_state =
										'changed';
								} else {
									this.formData.planConf.insuranceCarvesselCurrentAmount_state =
										'';
								}
							},
						},
					},
					{
						label: '车船税差价',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCarvesselDiffAmount',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						min: -Infinity,
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '商业险测算金额(年)',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCommercialQuondamAmount',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '本次商业险金额(年)',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCommercialCurrentAmount',
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
						event: {
							type: 'change',
							cb: row => {
								if (
									this.notEmpty(
										row.insuranceCommercialCurrentAmount,
									)
								) {
									this.formData.planConf.insuranceCommercialCurrentAmount_state =
										'changed';
								} else {
									this.formData.planConf.insuranceCommercialCurrentAmount_state =
										'';
								}
							},
						},
					},
					{
						label: '商业险差价',
						placeholder: '请输入金额',
						type: 'input_number',
						prop: 'insuranceCommercialDiffAmount',
						state: this.type == 'preview' ? 'readonly' : 'disabled',
						min: -Infinity,
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '保险询价附件',
						type: 'upload',
						prop: 'insuranceConsultAccessory',
						prototype: {
							listType: 'text',
							isShowTip: false,
							fileType: [
								'png',
								'jpg',
								'jpeg',
								'doc',
								'xls',
								'ppt',
								'txt',
								'pdf',
							],
						},
						span: 3,
						uploadEnd: () => {
							this.$refs.form1.form_clearValidate(
								'insuranceConsultAccessory',
							);
						},
					},
				];
			},
		},
		async created() {
			try {
				await this.getProductList();
				this.formData.plan ??= {};
				const unwatch = this.$watch(
					'formData.insuranceStandardType',
					(newValue, oldValue) => {
						this.initDetaultInsuranceList(newValue);
						unwatch && unwatch?.();
					},
					{
						immediate: true,
					},
				);

				// const unwatchInit = this.$watch(
				//     "formData",
				//     (newValue, oldValue) => {
				//         this.initDefault();
				//         unwatchInit && unwatchInit?.();
				//     },
				//     {
				//         immediate: true,
				//     }
				// );

				this.formData.sequenceNumber = this.getKey();
				this.formData.insuranceCompulsoryQuondamAmount ??= undefined;

				this.getDecorationList();
			} catch (error) {
				console.log(error);
			}
		},
		mounted() {
			this.$emitter.on('initDetaultData', this.initDetaultResult);

			// this.$emitter.on('getDecorationList', this.getDecorationList);
			this.$emitter.on('setQuoterCalcParam', this.setQuoterCalcParam);

			this.$emitter.on(
				'setInsuranceCarvesselCurrentAmount',
				this.setInsuranceCarvesselCurrentAmount,
			);
			this.$emitter.on('setchangeState', this.setchangeState);
			this.$emitter.on('initInputState', this.initInputState);
			this.$emitter.on('initCalcData', this.initCalcData);
			this.initDefault();
		},
		methods: {
			initDetaultResult() {
				this.$nextTick(() => {
					let data = {
						sequenceNumber: this.getKey(),
						plan: {
							planDriverType: '2',
							planFuelType: '2',
						},
						maintenanceMileageType: '1',
						insuranceList: [],
						maintenanceList: [],
						attachedDecorationList: [],
						feeList: [],
						planConf: {},
						substituteControlLevelType: '2',
					};
					if (this.config.businessSource == '2') {
						data.plan.planPaymentMethodType = '2';
						data.plan.planPeriod = 0;
					}
					this.formData = Object.assign(data);
				});
			},
			getKey() {
				let num = Math.random() * 100;
				let key =
					(this.details?.productList?.[this.index - 2]
						?.sequenceNumber ?? 0) +
					1 +
					this.index;
				return key;
			},
			isCurrentPruduction(sequenceNumber) {
				if (
					sequenceNumber.toString() !==
					this.formData.sequenceNumber.toString()
				) {
					return false;
				}
				return true;
			},
			initDefault() {
				if (
					this.formData.planConf &&
					typeof this.formData.planConf == 'string'
				) {
					try {
						this.formData.planConf =
							JSON.parse(this.formData.planConf) || {};
					} catch (error) {
						this.formData.planConf = {};
						console.log(error);
					}
				} else {
					// if (this.Empty(this.formData.planConf)) {
					this.formData.planConf = {};
					// }
				}
			},
			// 设置输入框是否更改
			setchangeState() {
				if (
					Object.prototype.toString.call(this.formData.planConf) ==
					'[object Object]'
				) {
					this.formData.planConf = JSON.stringify(
						this.formData.planConf,
					);
				}
			},
			setInsuranceCarvesselCurrentAmount(sequenceNumber) {
				if (!this.isCurrentPruduction(sequenceNumber)) return;
				this.formData.insuranceCarvesselQuondamAmount = 0;
				this.formData.insuranceCarvesselCurrentAmount = 0;
			},
			async getProductList() {
				return new Promise(resolve => {
					Promise.all([
						this._getDicts('pro_duct_in_sur_ance_a'),
						this._getDicts('pro_duct_in_sur_ance_b'),
						this._getDicts('pro_duct_in_sur_ance_c'),
						this.getInsuranceList(),
					])
						.then(values => {
							this.dicts.productA = values?.[0];
							this.dicts.productB = values?.[1];
							this.dicts.productC = values?.[2];
						})
						.finally(() => {
							resolve();
						});
				});
			},
			// 商业险险种
			async getInsuranceList() {
				return new Promise(resolve => {
					apis.Insurance({})
						.then(res => {
							if (res.code == 200) {
								this.insuranceList = res.data;
							}
						})
						.finally(() => {
							resolve();
						});
				});
			},
			setQuoterCalcParam(params) {
				let arr = params ?? this.getComputeParams(this.details);
				if (this.notEmpty(arr)) {
					this.details.quoterCalcParam = JSON.stringify(arr);
					// this.details.quoterCalcParam = this.Base64.encode(
					//     JSON.stringify(arr)
					// );
				}
			},
			getComputeParams(details, formData) {
				let that = this;
				let list = formData ?? details?.productList;
				return {
					quotationProductSchemeId: details.schemeId,
					customerTypeId: details.customerType,
					calcItemList: that.getComputeParamsBody(list),
				};
			},
			getComputeParamsBody(productList) {
				let list = [];
				let planPaymentFrequencyTypeList = [
					{
						key1: '0',
						key2: '1',
					},
					{
						key1: '1',
						key2: '3',
					},
					{
						key1: '2',
						key2: '6',
					},
					{
						key1: '3',
						key2: '12',
					},
				];
				if (
					Object.prototype.toString.call(productList) ==
					'[object Array]'
				) {
					list = productList;
				} else if (
					Object.prototype.toString.call(productList) ==
					'[object Object]'
				) {
					list = [productList];
				}
				let ratio =
					this.config?.quotationProductSchemeRule
						?.contractDepositMinimumRentMonths;
				let productListItem = this._.cloneDeep(
					this.details?.productList[0],
				);
				let arr = list?.map(formData => {
					let paymentMethod = planPaymentFrequencyTypeList.find(e => {
						return (
							e.key2 ==
							formData?.plan?.planPaymentFrequencyType?.toString()
						);
					})?.key1;

					let result = {
						paymentMethod, //支付方法
						salePrice: formData.plan.purchasePrice, //原新车采购价
						leaseTerm: formData.plan.planTenancyType, // 租赁期限(月）
						sequenceNumber: formData.sequenceNumber,
						carld: formData.plan.carId,
						count: formData.plan.quantityRequired, //台数
						carCurrentAppraisal: formData.plan.carCurrentAppraisal, //当期评估价
						billingMethod: formData.plan.planBillType, //账单生成方式
						accountPeriod: formData.plan.planPeriod, // 账期
						// 首期租金比例（%）
						firstInstallmentRentalRatio: formData.plan
							?.planFirstRentProportion
							? isNaN(
									formData.plan?.planFirstRentProportion /
										100,
							  )
								? null
								: formData.plan?.planFirstRentProportion / 100
							: null,
						// 保证金比例（%）
						planCashdepositProportion: formData.plan
							?.planCashdepositProportion
							? isNaN(
									formData.plan?.planCashdepositProportion /
										100,
							  )
								? null
								: formData.plan?.planCashdepositProportion / 100
							: null,
						carModelId: formData.plan.carModelId, //车型id
						// 年行驶公里数 #
						annualKilometers:
							productListItem.maintenanceAnnualMileageKey,
						vehicleUse: formData.plan.operationType, //车辆使用性质
						registrationCityId: formData.carCalcCityKey,
						vehicleUseCityId: formData.carCalcCityKey, // 用车城市
						// 上牌费（台）
						registrationFee: this.getChangedVal(
							formData,
							'carLicensePrice',
							formData,
						),

						// 限牌城市牌照费（台）
						restrictedLicenseFee: this.getChangedVal(
							formData,
							'carLicenseCityPrice',
							formData,
						),
						gpsFee: this.getChangedVal(
							formData.plan,
							'gpsFee',
							formData,
						),
						// 预计起租日期
						leaseStartDate: formData?.plan?.planTimeStart
							? this.A_formatTime(formData.plan.planTimeStart, 0)
							: null,
						// 支付时间
						paymentTimeMethod: formData.plan.planPaymentMethodType,
						// 首期租金
						firstInstallmentRent: this.getChangedVal(
							formData.plan,
							'planFirstRent',
							formData,
						),
						// 合同保证金
						contractDeposit: this.getChangedVal(
							formData.plan,
							'planContractCashdeposit',
							formData,
						),
						// 违章保证金
						violationDeposit: this.getChangedVal(
							formData.plan,
							'planViolationCashdeposit',
							formData,
						),
						periodicRent: formData.plan?.planRent, //每期租金
						// APR（%）
						pricingIrr: formData.plan?.planPricingIrr
							? formData.plan.planPricingIrr / 100
							: null,
						// 倍率
						contractDepositMinimumRentMonths: ratio,
						// 残值
						residualValueParam: {
							inputResidualValueRate: formData.plan
								?.planResidualProportion
								? isNaN(
										formData.plan?.planResidualProportion /
											100,
								  )
									? null
									: formData.plan?.planResidualProportion /
									  100
								: null,
							residualValue:
								this.details?.carType == '2' &&
								this.details?.carSourceType == '1' &&
								this.details?.rentType_raw == '1'
									? this.getChangedVal(
											formData?.plan,
											'finalEvaluationPrice',
											formData,
									  )
									: this.getChangedVal(
											formData?.plan,
											'planBalancepayment',
											formData,
									  ),
						},
						logisticFee: formData.plan?.logisticFee, //物流费
						warehouseOutCharge: formData.plan?.warehouseOutCharge, // 出库费
						alternativeCarParam: {
							alternativeCarLevelId:
								formData.substituteMaintenanceLevelType,
							enableRestrictedSubstituteCar:
								formData.substituteControlLevelType == '1'
									? 1
									: formData.substituteControlLevelType == '2'
									? 0
									: null,
							// 维保替代车价格（月）
							alternativeCarFee: this.getChangedVal(
								formData,
								'substituteMaintenanceRent',
								formData,
							),
							// 限行替代车价格（月）
							restrictedSubstituteCarFee: this.getChangedVal(
								formData,
								'substituteControlRent',
								formData,
							),
						},
						finalEvaluationPrice:
							this.details?.carType == '2' &&
							this.details?.carSourceType == '1' &&
							this.details?.rentType_raw == '1'
								? this.getChangedVal(
										formData?.plan,
										'finalEvaluationPrice',
										formData,
								  )
								: undefined,
						decorationParam: {
							totalDecorationPrice: null,
							decorationList: formData?.attachedDecorationList
								?.map(item => {
									if (
										this.notEmpty(item.decorationVal) &&
										this.notEmpty(item.decorationCount) &&
										this.notEmpty(item.decorationPrice)
									) {
										return {
											decorationName: item.decorationVal,
											count: item.decorationCount,
											price: Number(item.decorationPrice),
										};
									}
								})
								?.filter(item => this.notEmpty(item)),
						},
						otherParam: {
							totalOtherPrice: null,
							otherItemList: formData?.feeList
								?.map(item => {
									if (
										this.notEmpty(item.feeVal) &&
										this.notEmpty(item.feeCount) &&
										this.notEmpty(item.feeAmount)
									)
										return {
											otherItemName: item.feeVal,
											count: item.feeCount,
											price: Number(item.feeAmount),
										};
								})
								?.filter(item => this.notEmpty(item)),
						},
						insuranceParam: {
							// 本次交强险金额
							annualCompulsoryInsurance: this.getIn(formData)
								? formData.insuranceCompulsoryCurrentAmount
								: undefined,
							// annualCompulsoryInsurance: this.getChangedVal(
							//     formData,
							//     "insuranceCompulsoryCurrentAmount"
							// ),
							// 本次车船税金额
							annualVehicleTax: this.getIn(formData)
								? formData.insuranceCarvesselCurrentAmount
								: undefined,
							// annualVehicleTax: this.getChangedVal(
							//     formData,
							//     "insuranceCarvesselCurrentAmount"
							// ),
							// 本次商业险金额
							annualCommercialInsurance: this.getIn(formData)
								? formData.insuranceCommercialCurrentAmount
								: undefined,
							// annualCommercialInsurance: this.getChangedVal(

							//     formData,
							//     "insuranceCommercialCurrentAmount"
							// ),
							//购买类型
							insuranceBuyType: productListItem.insuranceBuyType,
							// 保险公司
							insuranceCompanyId:
								productListItem.insuranceCompanyKey,
							// 保险列表
							insuranceItemList: productListItem?.insuranceList
								?.map(item => {
									if (
										this.notEmpty(item.insuranceItemNameVal)
									) {
										return {
											isInsured:
												item.selectedType == '1'
													? '1'
													: '0',
											insuranceItemId:
												item.insuranceItemNameKey,
											insuranceItemName:
												item.insuranceItemNameVal,
											coverageAmount: item.sumInsuredVal,
										};
									}
								})
								?.filter(item => this.notEmpty(item)),
						},

						modelSeriesCategory: formData.plan?.carSeriesTypeKey, // 车辆分类
						maintenanceParam: {
							maintenanceAdjustmentFactor:
								formData.plan?.carSeriesTypeVal, // 车辆系数
							//是否包含维保
							includeMaintenance:
								productListItem.maintenanceType == '1'
									? 1
									: productListItem.maintenanceType == '2'
									? 0
									: null,
							//维保套餐
							maintenancePackageId:
								this.config.businessSource == '2'
									? productListItem.maintenanceMealType
									: null,
							//供应商
							maintenanceSupplierType:
								this.config.businessSource == '1'
									? productListItem.maintenanceSupplierId == 1
										? 1
										: productListItem.maintenanceSupplierId ==
										  2
										? 2
										: null
									: null,
							// 维保费用（月）
							monthlyMaintenanceFee: this.getChangedVal(
								formData,
								'maintenancePrice',
								formData,
							),
						},
					};
					this.initDeep(result);
					return result;
				});
				return arr;
			},
			// 保险是否被修改
			getIn(productListItem) {
				if (productListItem.plan.isGreen == 1) {
					if (
						this.Empty(
							productListItem?.insuranceCompulsoryCurrentAmount,
						) &&
						this.Empty(
							productListItem?.insuranceCommercialCurrentAmount,
						)
					) {
						return false;
					}
				} else {
					if (
						this.Empty(
							productListItem?.insuranceCompulsoryCurrentAmount,
						) &&
						this.Empty(
							productListItem?.insuranceCarvesselCurrentAmount,
						) &&
						this.Empty(
							productListItem?.insuranceCommercialCurrentAmount,
						)
					) {
						return false;
					}
				}
				if (
					productListItem?.planConf
						?.insuranceCompulsoryCurrentAmount_state == 'changed' ||
					productListItem?.planConf
						?.insuranceCarvesselCurrentAmount_state == 'changed' ||
					productListItem?.planConf
						?.insuranceCommercialCurrentAmount_state == 'changed'
				) {
					return true;
				}
			},
			getChangedVal(data, property, formData) {
				if (formData?.planConf?.[`${property}_state`] == 'changed') {
					return data?.[`${property}`];
				} else {
					return undefined;
				}
			},
			initCalcData(sequenceNumber) {
				let formData = this.formData;
				if (formData?.sequenceNumber == sequenceNumber) {
					// 上牌费（台）
					formData.carLicensePrice = undefined;
					// 限牌城市牌照费（台）
					formData.carLicenseCityPrice = undefined;
					// 维保替代车价格（月）
					formData.substituteMaintenanceRent = undefined;
					// 限行替代车价格（月）
					formData.substituteControlRent = undefined;

					// 首期租金
					formData.plan.planFirstRent = undefined;
					// 合同保证金
					formData.plan.planContractCashdeposit = undefined;
					// 违章保证金
					formData.plan.planViolationCashdeposit = undefined;
					// 尾款
					formData.plan.planBalancepayment = undefined;

					// 本次交强险金额(年)
					formData.insuranceCompulsoryCurrentAmount = undefined;
					// 本次车船税金额(年)
					formData.insuranceCarvesselCurrentAmount = undefined;
					// 本次商业险金额(年)
					formData.insuranceCommercialCurrentAmount = undefined;

					// 交强险测算金额(年)
					formData.insuranceCompulsoryQuondamAmount = undefined;
					// 车船税测算金额(年)
					formData.insuranceCarvesselQuondamAmount = undefined;
					// 商业险测算金额(年)
					formData.insuranceCommercialQuondamAmount = undefined;
					// 月租金
					formData.plan.planRent = undefined;

					formData.plan.gpsFee = undefined;
				}
			},
			initInputState(sequenceNumber) {
				if (!this.isCurrentPruduction(sequenceNumber)) return;
				let formData = this.formData;
				formData.planConf = {};
				// // 上牌费（台）
				// formData.carLicensePrice_state = "";
				// // 限牌城市牌照费（台）
				// formData.carLicenseCityPrice_state = "";
				// // 维保替代车价格（月）
				// formData.substituteMaintenanceRent_state = "";
				// // 限行替代车价格（月）
				// formData.substituteControlRent_state = "";

				// // 首期租金
				// formData.plan.planFirstRent_state = "";
				// // 合同保证金
				// formData.plan.planContractCashdeposit_state = "";
				// // 违章保证金
				// formData.plan.planViolationCashdeposit_state = "";
				// // 尾款
				// formData.plan.planBalancepayment_state = "";

				// // 本次交强险金额(年)
				// formData.insuranceCompulsoryCurrentAmount_state = "";
				// // 本次车船税金额(年)
				// formData.insuranceCarvesselCurrentAmount_state = "";
				// // 本次商业险金额(年)
				// formData.insuranceCommercialCurrentAmount_state = "";

				// // 月租金
				// formData.plan.planRent_state = "";
			},
			initDeep(obj) {
				if (typeof obj !== 'object') return;
				for (const key in obj) {
					if (Object.hasOwnProperty.call(obj, key)) {
						let element = obj[key];
						if (typeof element == 'object') {
							this.initDeep(element);
						} else {
							if (
								element === null ||
								element === undefined ||
								element === '' ||
								// element === 0 ||
								element === -1
							) {
								obj[key] = null;
							}
						}
					}
				}
			},
			// 测算
			compute(loading = false) {
				return new Promise((resolve, reject) => {
					if (
						this.details?.carType == '2' &&
						this.details?.carSourceType == '1' &&
						this.details?.rentType_raw == '1'
					) {
						if (
							this.Empty(
								this.formData?.plan?.finalEvaluationPrice,
							)
						) {
							let error = document.querySelector(
								'.finalEvaluationPrice',
							);
							error?.scrollIntoView({
								behavior: 'smooth',
								block: 'center',
							});
							this.$message({
								type: 'error',
								message: '请先输入到期评估价',
							});
							reject();
							return;
						}
					}
					if (loading) {
						this.$modal.loading('正在测算，请稍后...');
					}
					let params = this.getComputeParams(
						this.details,
						this.formData,
					);
					console.log('测算');
					this.setQuoterCalcParam(params);
					apis.Calc(params)
						.then(res => {
							if (res.code == 200) {
								if (loading) {
									this.$message({
										message: '测算成功！',
										type: 'success',
									});
								}
								let data = res.data.calcItemList[0];
								this.$nextTick(() => {
									this.setComputeResult(
										data,
										params.calcItemList[0],
									);
								});
								resolve();
							} else {
								throw new Error();
							}
						})
						.catch(err => {
							console.log(err);
							reject();
						})
						.finally(() => {
							if (loading) {
								this.$modal.closeLoading();
							}
						});
				});
			},
			setRowOrUndefined(row) {
				if (row === '' || row === null || row === undefined) {
					return undefined;
				} else {
					return row;
				}
			},

			// 设置测算结果
			setComputeResult(data, params) {
				let that = this;
				let productListItem = this.details?.productList[0];
				let planPaymentFrequencyTypeList = [
					{
						key1: '0',
						key2: '1',
					},
					{
						key1: '1',
						key2: '3',
					},
					{
						key1: '2',
						key2: '6',
					},
					{
						key1: '3',
						key2: '12',
					},
				];
				this.formData.plan.carModelId = this.setRowOrUndefined(
					data.carModelId,
				);
				// 销售价格、采购价
				this.formData.plan.purchasePrice = this.setRowOrUndefined(
					data.salePrice,
				);
				this.formData.plan.planTenancyType = data.leaseTerm;
				productListItem.maintenanceAnnualMileageKey =
					data.annualKilometers;
				this.formData.plan.operationType = data.vehicleUse?.toString();
				this.formData.carCalcCityKey = data.registrationCityId; // 上牌城市
				// vehicleUseCityId: "", // 用车城市
				this.formData.carLicensePrice = this.setRowOrUndefined(
					data.registrationFee,
				);
				this.formData.carLicensePrice_calc = this.setRowOrUndefined(
					data.registrationFee,
				);
				this.formData.carLicenseCityPrice = this.setRowOrUndefined(
					data.restrictedLicenseFee,
				);
				// this.formData.plan.carGuidePrice = data.salePrice; // 销售价格
				// this.formData.plan.planTimeStart = this.A_formatTime(
				//     data.leaseStartDate,
				//     1
				// );
				this.formData.plan.planPaymentMethodType =
					data.paymentTimeMethod;
				this.formData.plan.planFirstRent = this.setRowOrUndefined(
					data.firstInstallmentRent,
				);

				this.formData.plan.planViolationCashdeposit =
					this.setRowOrUndefined(data.violationDeposit);
				this.formData.plan.planRent = this.setRowOrUndefined(
					data.periodicRent,
				);
				this.formData.plan.planPricingIrr = data?.pricingIrr
					? this.setRowOrUndefined(data?.pricingIrr * 100)
					: null;
				this.formData.substituteMaintenanceRent =
					this.setRowOrUndefined(
						data?.alternativeCarCalcResult?.alternativeCarFee,
					);
				this.formData.substituteControlRent = this.setRowOrUndefined(
					data?.alternativeCarCalcResult?.restrictedSubstituteCarFee,
				);
				// 交强险测算金额(年)
				this.formData.insuranceCompulsoryQuondamAmount =
					this.setRowOrUndefined(
						data?.insuranceCalcResult
							?.calcAnnualCompulsoryInsurance,
					);
				// if (!this.getIn()) {
				//     this.formData.insuranceCompulsoryQuondamAmount =
				//         this.setRowOrUndefined(
				//             data?.insuranceCalcResult?.annualCompulsoryInsurance
				//         ) ?? this.formData.insuranceCompulsoryCurrentAmount;
				// }
				// 本次交强险金额(年)
				this.formData.insuranceCompulsoryCurrentAmount =
					this.setRowOrUndefined(
						data?.insuranceCalcResult?.annualCompulsoryInsurance,
					);

				//车船税测算金额(年)
				this.formData.insuranceCarvesselQuondamAmount =
					this.setRowOrUndefined(
						data?.insuranceCalcResult?.calcAnnualVehicleTax,
					);
				// if (!this.getIn()) {
				//     this.formData.insuranceCarvesselQuondamAmount =
				//         this.setRowOrUndefined(
				//             data?.insuranceCalcResult?.annualVehicleTax
				//         ) ?? this.formData.insuranceCarvesselCurrentAmount;
				// }

				//本次车船税金额(年)
				this.formData.insuranceCarvesselCurrentAmount =
					this.setRowOrUndefined(
						data?.insuranceCalcResult?.annualVehicleTax,
					);

				// 商业险测算金额(年)
				this.formData.insuranceCommercialQuondamAmount =
					this.setRowOrUndefined(
						data?.insuranceCalcResult
							?.calcAnnualCommercialInsurance,
					);
				// if (!this.getIn()) {
				//     this.formData.insuranceCommercialQuondamAmount =
				//         this.setRowOrUndefined(
				//             data?.insuranceCalcResult?.annualCommercialInsurance
				//         ) ?? this.formData.insuranceCommercialCurrentAmount;
				// }

				// 本次商业险金额(年)
				this.formData.insuranceCommercialCurrentAmount =
					this.setRowOrUndefined(
						data?.insuranceCalcResult?.annualCommercialInsurance,
					);
				//购买类型
				productListItem.insuranceBuyType = this.setRowOrUndefined(
					data?.insuranceCalcResult?.insuranceBuyType,
				);
				//保险公司
				productListItem.insuranceCompanyKey = this.setRowOrUndefined(
					data?.insuranceCalcResult?.insuranceCompanyId,
				);

				let planPaymentFrequencyType =
					planPaymentFrequencyTypeList.find(
						e => e.key1 == data.paymentMethod?.toString(),
					)?.key2;
				//支付频率
				this.formData.plan.planPaymentFrequencyType =
					planPaymentFrequencyType;
				if (productListItem?.maintenanceType == '1') {
					console.log(this.formData.sequenceNumber);
					// 维保费用（月）
					this.formData.maintenancePrice =
						data?.maintenanceCalcResult?.monthlyMaintenanceFee;
					// 维保费用合计
					this.formData.maintenanceFee =
						data?.maintenanceCalcResult?.totalMaintenanceFee;
				} else {
					this.formData.maintenancePrice = 0;
				}
				if (
					this.formData.planConf?.monthlyMaintenanceFee_state ==
					'changed'
				) {
					this.formData.maintenancePriceQuondam = -1;
				} else {
					this.formData.maintenancePriceQuondam =
						data?.maintenanceCalcResult?.monthlyMaintenanceFee;
				}
				// this.formData.maintenanceMealType =
				//     data?.maintenanceCalcResult?.maintenancePackageId;

				this.formData?.maintenanceList?.map(item => {
					let e =
						data?.maintenanceCalcResult?.maintenanceServiceList?.find(
							e =>
								e.maintenanceServiceName?.toString() ==
								item?.maintenanceItemTypeStr?.toString(),
						);
					if (e) {
						this.$set(item, 'maintenanceCount', e.count);
						this.$set(item, 'maintenanceFee', e.maintenanceFee);
					}
				});

				this.formData.plan.planTotalInvestment =
					data.totalInvestmentByCompany; // 投入总额

				// if (
				//     // this.Empty(this.formData?.plan?.planContractCashdeposit) &&
				//     this.formData?.planConf?.planContractCashdeposit_state !==
				//         "changed" &&
				//     data.contractDeposit == 0
				// ) {
				//     let ratio =
				//         this.config?.quotationProductSchemeRule
				//             ?.contractDepositMinimumRentMonths;

				//     if (this.notEmpty(ratio)) {
				//         console.log("合同保证金倍数：" + ratio);
				//         let planContractCashdeposit = this.numberRide(
				//             data.periodicRent,
				//             ratio
				//         );
				//         this.formData.plan.planContractCashdeposit = isNaN(
				//             planContractCashdeposit
				//         )
				//             ? undefined
				//             : planContractCashdeposit;

				//         this.formData.planConf.planContractCashdeposit_state =
				//             "changed";
				//         this.$emitter.emit(
				//             "clearVaild_downStream",
				//             "planContractCashdeposit"
				//         );
				//     } else {
				//         console.log("没有配置合同保证金倍数");
				//     }
				// } else {
				//     this.formData.plan.planContractCashdeposit =
				//         this.setRowOrUndefined(data.contractDeposit);
				// }

				// 合同保证金
				this.formData.plan.planContractCashdeposit =
					this.setRowOrUndefined(data.contractDeposit);
				this.formData.carPurchaseTax = data.purchaseTax;
				this.formData.plan.planResidual =
					data?.residualValueCalcResult?.residualValue;
				// 残值比例（%）
				this.formData.planResidualProportion = data
					?.residualValueCalcResult?.inputResidualValueRate
					? this.numberRide(
							data?.residualValueCalcResult
								?.inputResidualValueRate,
							100,
					  )
					: undefined;
				// 尾款(残值)
				this.formData.plan.planBalancepayment =
					data?.residualValueCalcResult?.residualValue;
				// 到期评估价
				if (
					this.details?.carType == '2' &&
					this.details?.carSourceType == '1' &&
					this.details?.rentType_raw == '1'
				) {
					this.formData.plan.finalEvaluationPrice =
						data?.residualValueCalcResult?.residualValue;
				}
				// GPS费用
				this.formData.plan.gpsFee = data.gpsFee;
				//  年检费

				this.formData.plan.annualCheckFee = data?.annualInspectionFee;
				let totalPrice = this.getTotalPrice(this.formData);
				if (
					totalPrice !== 0 &&
					totalPrice !== '0' &&
					totalPrice !== '-' &&
					data.firstInstallmentRent !== 0 &&
					data.firstInstallmentRent !== '0' &&
					this.Empty(this.formData.plan?.planFirstRentProportion)
				) {
					let firstInstallmentRentRatio = this.numberExcept(
						Number(data.firstInstallmentRent),
						totalPrice,
					);

					this.formData.plan.planFirstRentProportion =
						this.numberRide(firstInstallmentRentRatio, 100);
				}
				// this.initInputState();
				this.$forceUpdate();
			},
			getTotalPrice(row) {
				let p = 0;

				let monthlyRent = this.numberExcept(
					row?.plan?.planRent,
					row?.plan?.planPaymentFrequencyType,
				);
				if (monthlyRent && row?.plan?.planTenancyType) {
					p =
						this.numberRide(
							monthlyRent,
							row?.plan?.planTenancyType,
						) * 1;
				}
				if (this.value.rentType_raw == '1') {
					return p;
				} else {
					let price =
						p +
						(row?.plan?.planBalancepayment * 1 ?? 0) +
						(row?.plan?.planFirstRent * 1 ?? 0);
					return isNaN(price) ? '-' : price;
				}
			},
			showCollapse() {},
			// 新增 块
			push() {
				this.details.productList ??= [];
				let data = {
					// sequenceNumber: new Date().getTime().toString(),
					plan: { planDriverType: '2', planFuelType: '2' },
					maintenanceMileageType: '1',
					insuranceList: [],
					maintenanceList: [],
					attachedDecorationList: [],
					feeList: [],
					substituteControlLevelType: '2',
				};
				if (this.config.businessSource == '2') {
					data.plan.planPaymentMethodType = '2';
					data.plan.planPeriod = 0;
				}
				this.details.productList.push(data);
			},
			// 删除 块
			pop() {
				let type =
					this.details.carType == '2' &&
					this.details.carSourceType == '2'
						? '车辆报价'
						: '车型报价';
				this.$confirm(
					`此操作将删除${type}${this.index}, 是否继续?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					},
				)
					.then(() => {
						this.details.productList.splice(this.index - 1, 1);
					})
					.catch(err => {
						console.log(err);
					});
			},
			// 删除 险种
			remove(index, row, list) {
				this.$confirm(
					`此操作将删除 ${
						row?.insuranceItemNameVal
							? row?.insuranceItemNameVal + '险种'
							: '该险种'
					}, 是否继续?`,
					'提示',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					},
				)
					.then(() => {
						list.splice(index, 1);
					})
					.catch(() => {});
			},
			// 新增 险种
			add(list) {
				list.push({
					insuranceItemNameKey: '',
					insuranceItemNameVal: '',
					selectedType: '1',
					operationType: '1',
					irrespectiveType: '1',
					sumInsuredVal: undefined,
					isCoverageAmount: '1',
					coverageAmountList: JSON.stringify(
						this.defaultsumInsurList,
					),
					tag: true,
				});
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
			setHeaderCellName({ columnIndex }) {
				if (this.state == 'readonly') {
					return '';
				}
				if (columnIndex !== 0 && columnIndex !== undefined) {
					return 'ruleHeaderCell';
				}
			},

			initDetaultInsuranceList(type, clear) {
				let insuranceArr = [],
					insuranceList = this._.cloneDeep(
						this.formData.insuranceList,
					);
				if (type == '') {
					return;
				}
				this.$set(this.formData, 'insuranceList', []);
				let list = [];
				if (type == '4') {
					list = this._.cloneDeep(this.insuranceList);
				} else {
					list = this.getFilterInsuranceList(type);
				}
				// 获取套餐内险种
				list?.map(item => {
					let child = insuranceList?.find(e => {
						return e.insuranceItemNameVal == item.insuranceItemName;
					});
					if (!child) child = {};
					// insuranceArr.push({
					//     ...child,
					//     selectedType: "1",
					//     operationType: "2",
					//     irrespectiveType: "1",
					//     coverageAmountList: JSON.stringify(item.coverageAmountList),
					// });
					insuranceArr.push({
						...child,
						insuranceItemNameKey: item.insuranceItemId,
						insuranceItemNameVal: item.insuranceItemName,
						isCoverageAmount: item.isCoverageAmount?.toString(),
						coverageAmountList: JSON.stringify(
							item.coverageAmountList,
						),
						selectedType: child.selectedType ?? '1',
						operationType: '2',
						irrespectiveType: '1',
						sumInsuredVal:
							type == '4'
								? child.sumInsuredVal
								: item.sumInsuredVal?.toString(),
					});
				});
				//  获取自定义险种
				if (!clear) {
					insuranceList?.map(item => {
						if (item.operationType == '1') {
							insuranceArr.push(item);
						}
					});
				}
				this.formData.insuranceList = insuranceArr;
			},
			getFilterInsuranceList(type) {
				let dictList = [];
				switch (type) {
					case '1':
						// dictList = await this._getDicts("pro_duct_in_sur_ance_a");
						dictList = this.dicts.productA;
						break;
					case '2':
						// dictList = this.dict.type.pro_duct_in_sur_ance_b;
						dictList = this.dicts.productB;
						break;
					case '3':
						dictList = this.dicts.productC;
						// dictList = this.dict.type.pro_duct_in_sur_ance_c;
						break;
				}
				let list = this.insuranceList.map(item => {
					let child = dictList.find(e => {
						return (
							e.dictLabel?.trim() ==
							item.insuranceItemName?.trim()
						);
					});
					let obj = {
						...item,
					};
					if (child?.remark) {
						let price = child.remark?.trim() * 1;
						obj.sumInsuredVal = price;
					}

					if (this.notEmpty(child)) {
						return obj;
					}
				});
				return list.filter(e => this.notEmpty(e));
			},
			// 加装
			getDecorationList() {
				if (!this.formData?.plan?.carSeating) {
					this.refittedList = [];
					this.$set(this.formData, 'attachedDecorationList', []);
					return;
				}
				let params = {
					seat: this.formData.plan?.carSeating,
				};
				apis.Decoration(params).then(res => {
					if (res.code == 200) {
						this.refittedList = res.data;
						this.refittedList.push({
							decorationName: '其他',
							decorationFee: undefined,
						});
						// this.initDetaultRefittedList();
					}
				});
			},
			initDetaultRefittedList() {
				this.formData.attachedDecorationList = [];
				this.refittedList.map(item => {
					this.formData.attachedDecorationList.push({
						decorationVal: item.decorationName,
						decorationPrice: item.decorationFee,
						decorationCount: 0,
						operationType: '2',
						selectedType: '2',
						remark: '',
					});
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		// border: 1px solid black;
		// padding: 10px;
		margin: 20px;
		// box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		background-color: #fff;
		border-radius: 8px;
		// border: 1px solid #3eafff;
		.collapse {
			padding-top: 10px;
			::v-deep .el-collapse-item__header {
				padding: 0 20px;
			}
		}
		.nav {
			// margin: 0 20px 0;
			// margin: 16px 20px;
			// margin-bottom: 0;
			padding: 16px 0;
			display: flex;
			width: 100%;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1px solid #e9e9e9;
			.title {
				font-family: PingFangSC, PingFang SC;
				font-weight: 500;
				font-size: 16px;
				color: #333333;
				line-height: 22px;
				text-align: left;
				font-style: normal;
			}
		}
	}
	.chunk {
		margin: 20px;
		padding: 20px;
		border-radius: 8px;
		background-color: #fff;
		box-shadow: 0px 1px 3px 1px rgba(0, 28, 54, 0.11);
		.title {
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 22px;
			padding-bottom: 15px;
			border-bottom: 1px solid #e9e9e9;
		}
	}
	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 48px;
		background: #ffffff;
		border-radius: 4px;
		border: 1px solid #dadada;
		color: #1890ff;
		margin-top: 15px;
		font-size: 14px;
		cursor: pointer;
	}
	.content_table {
		background-color: #f7fbff;
		border-radius: 4px;
		padding: 16px;
		margin-top: 15px;
		.content_table-title {
			font-size: 14px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #464646;
			line-height: 22px;
			padding-bottom: 10px;
		}
	}
	.infoAll {
		display: flex;
		flex-direction: column;
		gap: 20px 0;
	}
	.carInfo {
		// margin-bottom: 15px;
	}
	.handleBox {
		padding: 0 20px;
		display: flex;
		justify-content: flex-end;
	}
</style>
